package com.ruoyi.web.wx.utils;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@Component
public class LockerPool {
    Map<String, String> lockers = new HashMap<String, String>();
 
    public String getLocker(String id) {
        if (!lockers.keySet().contains(id)) {
            /*try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            synchronized (LockerPool.class){
                if (!lockers.keySet().contains(id)) {
                    lockers.put(id, "Lock" + id);
                }
            }

        }
 
        return lockers.get(id);
    }

    private static Integer x=100;

    public static void setX(Integer x) {
        LockerPool.x = x;
    }

    public static Integer getX() {
        return x;
    }

    // 测试
    public static void main(String[] args) throws Exception {
        LockerPool pool = new LockerPool();
        final CountDownLatch latch = new CountDownLatch(2);

        Runnable runnableSub = new Runnable() {
            @Override
            public void run() {
                String locker = pool.getLocker("1");
                synchronized (locker){
                    Integer x1 = LockerPool.getX();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Integer x = x1-60;
                    LockerPool.setX(x);
                    System.out.println(Thread.currentThread().getName()+":提款60元");
                }
                latch.countDown();
            }
        };

        Runnable runnableAdd = new Runnable() {
            @Override
            public void run() {
                String locker = pool.getLocker("1");
                synchronized (locker){
                    Integer x1 = LockerPool.getX();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Integer x = x1+10;
                    LockerPool.setX(x);
                    System.out.println(Thread.currentThread().getName()+":存款10元");
                }
                latch.countDown();
            }
        };

        Thread thread1 = new Thread(runnableSub,"取现");
        Thread thread2 = new Thread(runnableAdd,"存款");
        thread1.start();
        thread2.start();
        latch.await();
        System.out.println("当前余额:"+LockerPool.getX());

    }
}

